/**
 * mount virtual dom to real dom
 */
;(function() {
  // 虚拟dom
  function vnode(tag, data, children, text) {
    this.tag = tag
    this.data = data
    this.children = children
    this.text = text
  }

  // 创建真实dom
  function createElm(vnode) {
    var tag = vnode.tag
    var data = vnode.data
    var children = vnode.children

    if (tag !== undefined) {
      vnode.elm = document.createElement(tag)

      // 有标签属性设置属性
      if (data.attrs !== undefined) {
        var attrs = data.attrs
        for (var k in attrs) {
          vnode.elm.setAttribute(k, attrs[k])
        }
      }
      // 有嵌套子节点，嵌套子节点
      if (children) {
        createChildren(vnode, children)
      }
    } else {
      // 非标签元素，创建文本标签
      vnode.elm = document.createTextNode(vnode.text)
    }
    return vnode.elm
  }

  // 递归创建嵌套子节点
  function createChildren(vnode, children) {
    for (var i = 0; i < children.length; i++) {
      vnode.elm.appendChild(createElm(children[i]))
    }
  }

  // diff 新旧节点
  function patch(oldVnode, vnode) {
    createElm(vnode)

    var isRealElement = oldVnode.nodeType !== undefined // virtual node has no `nodeType` property
    if (isRealElement) {
      var parent = oldVnode.parentNode
      if (parent) {
        parent.insertBefore(vnode.elm, oldVnode)
        parent.removeChild(oldVnode)
      }
    }
    return vnode.elm
  }

  function render() {
    return new vnode(
      'div',
      {
        attrs: {
          class: 'wrapper',
        },
      },
      [new vnode('p', { attrs: { class: 'inner' } }, [new vnode(undefined, undefined, undefined, 'Hello Vue?')])]
    )
  }

  // 挂载
  function mount(el) {
    var vnode = render()
    patch(el, vnode)
  }

  mount(document.querySelector('#app'))
})()
